#!/usr/bin/env python
# coding=utf-8
import math
import os
import glob
from PIL import Image, ImageTk
import shutil
import tkinter as tk
from tkinter import messagebox
from tkinter import  filedialog, Entry, Button, StringVar

def create_window(parent):
    global offX, offY
    offX = 60
    offY = 50

    # 裁剪图片边界区域
    global left_value, right_value, up_value, down_value
    left_value = 1
    right_value = 1
    up_value = 1
    down_value = 1

    global imgs_scale,imgs_Dic,dirName_Dic,scale_value, scale_index
    scale_value = 1
    imgs_Dic = {}
    dirName_Dic={}
    imgs_scale = []
    scale_index = 0

    # 创建窗口
    root = tk.Toplevel(parent)
    root.title("序列帧图片批处理")
    root.config(bg="grey")
    root.geometry("1000x1000+0+0")

    # 图像绘制位置坐标
    canvas = tk.Canvas(root, width=800, height=800, bg="gray")
    canvas.place(x=offX + 70, y=offY + 100)

    mainFile = u'生成'

    def select_directory(entry_var):
        """弹出选择目录对话框"""
        directory = filedialog.askdirectory(parent=root)
        entry_var.set(directory)
        root.lift()

    # 获取输入路径
    def get_input_path():
        global image_frames, last_button, next_button, image_frames_path, image_frames_path1, image_frames_output_path, image_frames_output_path1
        global all_directory_type, cur_directory_type_index
        # 路径一
        all_directory_type = []
        cur_directory_type_index = 0
        image_frames_path = entry_scale_frame_path.get().replace("\\", "/")
        if image_frames_path != '':
            image_frames_output_path = image_frames_path + "_output"
            all_directory = [d for d in os.listdir(image_frames_path) if
                             os.path.isdir(os.path.join(image_frames_path, d))]
            dir_name = ""
            for i, d in enumerate(all_directory):
                net_dir_name = os.path.basename(d)
                if dir_name.split("_")[0] == net_dir_name.split("_")[0]:
                    all_directory_type[-1].append(net_dir_name)
                else:
                    dir_name = net_dir_name
                    all_directory_type.append([dir_name])

        if not all_directory_type:
            messagebox.showerror("Error", "路径一没有目录")
            # return
    # 第一行：按钮+输入框
    entry_scale_frame_path = StringVar()
    entry_path = Entry(root, textvariable=entry_scale_frame_path)
    entry_path.place(x=offX + 350, y=offY -27)
    button1 = Button(root, text="输入目录", command=lambda: select_directory(entry_scale_frame_path),
                           bg='skyblue')
    button1.place(x=offX + 500, y=offY -30)

    # 第二行：输入框
    tk.Label(root, text="请输入高度", bg='green').place(x=offX + 350, y=offY+5)
    entry_scale_width = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale_width)
    entry_path1.place(x=offX + 420, y=offY+5)

    # 第三行：输入框
    tk.Label(root, text="请输入宽度", bg='green').place(x=offX + 350, y=offY + 35)
    entry_scale_height = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale_height)
    entry_path1.place(x=offX + 420, y=offY + 35)

    # 第四行：按钮
    button1 = Button(root, text="预览", command=lambda: load_images(),
                     bg='skyblue')
    button1.place(x=offX + 350, y=offY + 65)

    def btn_last_directory():
        global cur_directory_type_index,scale_index
        if cur_directory_type_index <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index -= 1
        scale_index = 0

    def btn_next_directory():
        global cur_directory_type_index,scale_index
        if cur_directory_type_index >= len(imgs_Dic) - 1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index += 1
        scale_index=0

    last_button = tk.Button(root, text="上一个", command=btn_last_directory)
    last_button.place(x=offX + 405, y=offY + 65)

    next_button = tk.Button(root, text="下一个", command=btn_next_directory)
    next_button.place(x=offX + 465, y=offY + 65)

    button2 = Button(root, text="导出", command=lambda: combine_photo(),
                     bg='skyblue')
    button2.place(x=offX + 530, y=offY + 65)

    def load_images():
        global imgs_scale, button_scale
        global button_scale_load, button_scale_sure, scale_value, input_folder, output_folder, imgs_scale_path,cur_directory_type_index

        #get_input_path()
        cur_directory_type_index = 0
        inputPath = entry_scale_frame_path.get()

        imageW = int(entry_scale_width.get())

        imageH = int(entry_scale_height.get())

        path = ''

        for x in inputPath:
            path += x
            if x == '\\':
                path += '\\'

        path = os.path.normpath(path)
        i=0
        for dirName in os.listdir(path):
            dealDir = path + '\\' + dirName
            dirName_Dic[i]=dirName
            cur_img = []
            i+=1
            print(dealDir)
            if os.path.isdir(dealDir) and dirName != mainFile:
                for pngName in os.listdir(dealDir):
                    if os.path.isfile(dealDir + '\\' + pngName):
                        img1 = Image.open(dealDir + '\\' + pngName)
                        img2 = transparent_back(img1)

                        str = pngName[0:-4]
                        saveFile = path + '\\' + mainFile + '\\' + dirName
                        if img2 != False:
                            toImage = Image.new('RGBA', (imageW, imageH), (255, 255, 255, 0))

                            print(u'处理图片', dealDir + '\\' + pngName)

                            pos = []
                            txtName = dealDir + '\\Placements\\' + str + '.txt'
                            print(u'打开目标txt', txtName)
                            fp = open(txtName, 'r')
                            done = False
                            while not done:
                                aline = fp.readline()
                                if aline != '' and aline != ' ':
                                    if int(aline):
                                        pos.append(int(aline))
                                    else:
                                        pos.append(0)
                                else:
                                    done = True
                            fp.close()
                            if len(pos) == 0:
                                pos = [0, 0]
                            r, g, b, a = img2.split()
                            toImage.paste(img2, (int(imageW / 2) + pos[0] - 24, int(imageH / 2) + pos[1] - 18))
                            cur_img.append(toImage)
            imgs_Dic[dirName] = cur_img
        print(dirName_Dic)
        print(imgs_Dic)
        update_frame_sclae()
    def CreateDir(path):

        isExists = os.path.exists(path)

        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            # 创建目录操作函数
            os.makedirs(path)

            print(path + u'创建成功')
            return True
        else:
            # 如果目录存在则不创建，并提示目录已存在
            # print(path+u'目录已存在')
            return False

    def transparent_back(img):
        img = img.convert('RGBA')
        L, H = img.size
        # if L == 1 or H == 1:
        # return False

        return img

    def combine_photo():
        inputPath = entry_scale_frame_path.get()

        imageW = int(entry_scale_width.get())

        imageH = int(entry_scale_height.get())

        path = ''

        for x in inputPath:
            path += x
            if x == '\\':
                path += '\\'

        path = os.path.normpath(path)
        CreateDir(os.path.join(path, mainFile))
        # CreateDir(path+'\\'+mainFile)

        # print(os.listdir(path))
        for dirName in os.listdir(path):
            dealDir = path + '\\' + dirName
            print(dealDir)
            if os.path.isdir(dealDir) and dirName != mainFile:
                for pngName in os.listdir(dealDir):
                    if os.path.isfile(dealDir + '\\' + pngName):
                        img1 = Image.open(dealDir + '\\' + pngName)
                        img2 = transparent_back(img1)

                        str = pngName[0:-4]
                        saveFile = path + '\\' + mainFile + '\\' + dirName
                        if img2 != False:
                            toImage = Image.new('RGBA', (imageW, imageH), (255, 255, 255, 0))

                            print(u'处理图片', dealDir + '\\' + pngName)

                            pos = []
                            txtName = dealDir + '\\Placements\\' + str + '.txt'
                            print(u'打开目标txt', txtName)
                            fp = open(txtName, 'r')
                            done = False
                            while not done:
                                aline = fp.readline()
                                if aline != '' and aline != ' ':
                                    if int(aline):
                                        pos.append(int(aline))
                                    else:
                                        pos.append(0)
                                else:
                                    done = True
                            fp.close()
                            if len(pos) == 0:
                                pos = [0, 0]
                            r, g, b, a = img2.split()
                            toImage.paste(img2, (int(imageW / 2) + pos[0] - 24, int(imageH / 2) + pos[1] - 18))

                            CreateDir(saveFile)
                            toImage.save(saveFile + '\\' + str + '.png')
                        else:
                            print(u'复制文件'),
                            shutil.copy(dealDir + '\\' + pngName, saveFile + '\\' + str + '.png')

    # 从目录加载图片
    # def find_png_files(directory):
    #     png_files = glob.glob(os.path.join(directory, '**', '*.png'), recursive=True)
    #     return png_files
    # def load_images_from_directory():
    #     global image_frames, image_frames1, image_frames2, image_frames3, cur_frame_index, cur_directory_type_index
    #     # image_paths = []
    #     # for i, d in enumerate(all_directory_type[cur_directory_type_index]):
    #     #     image_paths.extend(find_png_files(image_frames_path + "/" + d))
    #
    #     if not dirName_Dic[cur_directory_type_index] in imgs_Dic:
    #         messagebox.showerror("Error", "目录一没有图片文件")
    #
    #     cur_frame_index = 0
    #     #image_frames = [Image.open(path) for path in image_paths]
    #     image_frames=imgs_Dic[dirName_Dic[cur_directory_type_index]]
    #     print("当前图片序号："+str(cur_directory_type_index))
    #     print(image_frames)
    #     reset_window()
    # 重置窗口
    # def reset_window():
    #     global image_max_width, image_max_height, canvas_width, canvas_height, center_x, center_y, cur_frame_index
    #     image_max_width = 0
    #     image_max_height = 0
    #     canvas_width = 1000
    #     canvas_height = 1000
    #     center_x = 0
    #     center_y = 0
    #     cur_frame_index = 0
    #     for i, img in enumerate(image_frames):
    #         image_max_width = max(image_max_width, img.width)
    #         image_max_height = max(image_max_height, img.height)
    #     root_width = max(canvas_width, image_max_width)
    #     root_height = max(canvas_height, image_max_height)
    #     # 处理大图
    #     root.geometry(f"{root_width}x{root_height}")
    #     canvans_width = max(800, image_max_width)
    #     canvans_height = max(800, image_max_height)
    #     canvas.config(width=canvans_width, height=canvans_width)
    #     center_x = canvans_width / 2
    #     center_y = canvans_height / 2
        # 刷新帧率图片

    def update_frame_sclae():
        global imgs_scale, scale_index, photo, resized_img, name, root_after2
        if imgs_Dic[dirName_Dic[cur_directory_type_index]]:
            canvas.delete("all")
            length = len(imgs_Dic[dirName_Dic[cur_directory_type_index]])
            img_scale = imgs_Dic[dirName_Dic[cur_directory_type_index]][scale_index]
            #name = img_scale.filename.split("\\")[len(img_scale.filename.split("\\")) - 1]
            resize = [math.ceil(img_scale.size[0] * scale_value), math.ceil(img_scale.size[1] * scale_value)]
            resized_img = img_scale.resize(resize, Image.Resampling.LANCZOS)
            photo = ImageTk.PhotoImage(resized_img)
            x = int(photo.width() / 2)
            y = int(photo.height() / 2)

            canvas.create_rectangle(x - photo.width() / 2, y - photo.height() / 2, x + photo.width() / 2,
                                          y + photo.height() / 2, fill="white", outline="black")
            canvas.create_image(x, y, anchor=tk.CENTER, image=photo)

            canvas.create_line(left_value, up_value, right_value, up_value, fill="red")
            canvas.create_line(left_value, down_value, right_value, down_value, fill="red")
            canvas.create_line(left_value, up_value, left_value, down_value, fill="red")
            canvas.create_line(right_value, up_value, right_value, down_value, fill="red")

            scale_index = (scale_index + 1) % length  # 循环显示
        root_after2 = root.after(200, update_frame_sclae)
    #combine_photo()